package org.wanho.shop.servlet;

import org.wanho.shop.entity.User;
import org.wanho.shop.exception.LoginErrorException;
import org.wanho.shop.exception.UserExistsException;
import org.wanho.shop.service.UserService;
import org.wanho.shop.service.impl.UserServiceImpl;
import org.wanho.shop.vo.Cart;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Author：汤小洋
 * Date：2023-04-26 9:32
 * Description：<描述>
 */
@WebServlet("*.user")
public class UserServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getServletPath();
        if ("/login.user".equals(path)){
            login(req,resp);
        }else if("/register.user".equals(path)){
            register(req,resp);
        }else if("/logout.user".equals(path)){
            logout(req,resp);
        }
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        try {
            User user = userService.login(username, password);
            req.getSession().setAttribute("user",user);

            // 用户登录成功后，为其创建一个购物车，放到Session中
            req.getSession().setAttribute("cart", new Cart());


            resp.sendRedirect(req.getContextPath()+"/findAll.product");
        } catch (LoginErrorException e) {
            req.setAttribute("loginMsg",e.getMessage());
            req.getRequestDispatcher("/jsp/login.jsp").forward(req,resp);
        }
    }

    private void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");

        User user = new User(username,password,phone, address);
        try {
            userService.register(user);
            resp.sendRedirect(req.getContextPath()+"/jsp/login.jsp");
        } catch (UserExistsException e) {
            req.setAttribute("registerMsg",e.getMessage());
            req.getRequestDispatcher("/jsp/register.jsp").forward(req,resp);
        }
    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.getSession().invalidate();
        resp.sendRedirect(req.getContextPath()+"/findAll.product");
    }


}
